package com.kuanter.kuanterauto.net;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;

public class HttpUtil {
	/**
	 * 
	 * @param url
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	public static String requestStringForPost(String url,Context context) {
		String result = "";
		HttpPost post = new HttpPost(url);
		// if (!"".equals(sessionId)) {
		// post.setHeader("Cookie", "ASP.NET_SessionId=" + sessionId);
		// }
		// DefaultHttpClient httpClient = new DefaultHttpClient();
		// HttpClient httpClient = CustomerHttpClient.getHttpClient();
//		HttpClient httpClient = AndroidHttpClient.newInstance("Android");
//		HttpParams params = httpClient.getParams();
//		HttpConnectionParams.setConnectionTimeout(params, 30000);
//		HttpConnectionParams.setSocketBufferSize(params, 8192);
//		HttpClient httpClient = QHttpClientUtils.getHttpClient(HttpTask.proxyHost, HttpTask.proxyPort);
		HttpClient httpClient = QHttpClientUtils.getHttpClient(context);
		HttpResponse response;
		try {
			response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			} else {
				result = "网络连接错误";
				post.abort();
				return result;
			}
		} catch (Exception e) {
			post.abort();
			result = "网络连接错误";
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();

//			((AndroidHttpClient) httpClient).close();
		}
		return result;
	}

	/**
	 * utf8 编码
	 * 
	 * @param url
	 * @param sessionId
	 * @return
	 * @throws Exception
	 */
	public static String requestStringForPost_utf(String url,Context context) {
		String result = "";
		HttpPost post = null;
		HttpClient httpClient = null;
		try {
			post = new HttpPost(URLEncoder.encode(url, "UTF-8"));
			// if (!"".equals(sessionId)) {
			// post.setHeader("Cookie", "ASP.NET_SessionId=" + sessionId);
			// }
			// DefaultHttpClient httpClient = new DefaultHttpClient();
			// HttpClient httpClient = CustomerHttpClient.getHttpClient();
//			httpClient = AndroidHttpClient.newInstance("Android");
//			HttpParams params = httpClient.getParams();
//			HttpConnectionParams.setConnectionTimeout(params, 30000);
//			HttpConnectionParams.setSocketBufferSize(params, 8192);
//			 httpClient = QHttpClientUtils.getHttpClient(HttpTask.proxyHost, HttpTask.proxyPort);
			 httpClient = QHttpClientUtils.getHttpClient(context);
			HttpResponse response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			} else {
				result = "网络连接错误";
				post.abort();
				return result;
			}
		} catch (Exception e) {
			post.abort();
			result = "网络连接错误";
			e.printStackTrace();
		} finally {
//			((AndroidHttpClient) httpClient).close();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * // * 有参post //
	 */
	public static String requestStringForPost(String url,
			List<NameValuePair> params) {
		String result = null;
		HttpPost post = new HttpPost(url);
		// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
		// HTTP.UTF_8);
		// post.setEntity(entity);
		// HttpResponse response = new DefaultHttpClient().execute(post);
		// HttpResponse response =
//		// CustomerHttpClient.getHttpClient().execute(post);
//		HttpClient httpClient = AndroidHttpClient.newInstance("Android");
//		HttpParams params1 = httpClient.getParams();
//		HttpConnectionParams.setConnectionTimeout(params1, 30000);
//		HttpConnectionParams.setSocketBufferSize(params1, 8192);
//		HttpClient httpClient = QHttpClientUtils.getHttpClient(HttpTask.proxyHost, HttpTask.proxyPort);
		BasicHttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 1500);
		 HttpConnectionParams.setSoTimeout(httpParameters, 1500); 
		HttpClient httpClient = new DefaultHttpClient(httpParameters);
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			post.setEntity(entity);
			HttpResponse response = httpClient.execute(
					post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			} else {
				post.abort();
				result = "网络连接错误";
				return result;
			}
		} catch (Exception e) {
			result = "网络连接错误";
			e.printStackTrace();
		} finally {
//			((AndroidHttpClient) httpClient).close();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}
	
	/**
	 * // * 有参post //
	 */
	public static String requestStringForPost1(String url,
			List<NameValuePair> params) {
		String result = null;
		HttpPost post = new HttpPost(url);
		// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
		// HTTP.UTF_8);
		// post.setEntity(entity);
		// HttpResponse response = new DefaultHttpClient().execute(post);
		// HttpResponse response =
//		// CustomerHttpClient.getHttpClient().execute(post);
//		HttpClient httpClient = AndroidHttpClient.newInstance("Android");
//		HttpParams params1 = httpClient.getParams();
//		HttpConnectionParams.setConnectionTimeout(params1, 30000);
//		HttpConnectionParams.setSocketBufferSize(params1, 8192);
//		HttpClient httpClient = QHttpClientUtils.getHttpClient(HttpTask.proxyHost, HttpTask.proxyPort);
//		BasicHttpParams httpParameters = new BasicHttpParams();
//		HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
//		 HttpConnectionParams.setSoTimeout(httpParameters, 1000); 
		HttpClient httpClient = new DefaultHttpClient();
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			post.setEntity(entity);
			HttpResponse response = httpClient.execute(
					post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			} else {
				post.abort();
				result = "网络连接错误";
				return result;
			}
		} catch (Exception e) {
			result = "网络连接错误";
			e.printStackTrace();
		} finally {
//			((AndroidHttpClient) httpClient).close();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * get
	 */
	public static String requestStringForGet(String url,Context context) throws Exception {
		String result = "";
		HttpGet get = new HttpGet(url);
		// DefaultHttpClient httpClient = new DefaultHttpClient();
//		HttpClient httpClient = QHttpClientUtils.getHttpClient(HttpTask.proxyHost, HttpTask.proxyPort);
		HttpClient httpClient = QHttpClientUtils.getHttpClient(context);
		HttpResponse response = httpClient.execute(get);
		System.out.println(response.getStatusLine().getStatusCode());
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			result = EntityUtils.toString(response.getEntity());
			return result;
		} else {
			result = "网络连接错误";
			return result;
		}
	}

	/**
	 * post发送json
	 * 
	 */
	public static String SendRequest(String adress_Http, String strJson)
			throws Exception {
		String returnLine = "";
		URL my_url = new URL(adress_Http);
		HttpURLConnection connection = (HttpURLConnection) my_url
				.openConnection();
		connection.setDoOutput(true);

		connection.setDoInput(true);

		connection.setRequestMethod("POST");

		// if (!"".equals(sessionId)) {
		// connection.addRequestProperty("Cookie", "ASP.NET_SessionId="
		// + sessionId);
		// }

		connection.setUseCaches(false);

		connection.setInstanceFollowRedirects(true);

		connection.setRequestProperty("Content-Type", "application/json");

		connection.connect();

		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());

		byte[] content = strJson.getBytes("utf-8");

		out.write(content, 0, content.length);
		out.flush();
		out.close();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "utf-8"));
		String line = "";
		while ((line = reader.readLine()) != null) {
			returnLine += line;
			// System.out.println(line);
		}
		reader.close();
		return returnLine;

	}
	
	public static InputStream getStream(String url) {
		InputStream is = null;
		URL u;
		try {
			u = new URL(url);
			URLConnection conn = u.openConnection();
			conn.connect();
			is = conn.getInputStream();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
}
